<template>
    <div class="flex-container">
        <div class="map-container">
            <img :src="mapSrc" class="map-image" alt="Campus Map" @click="handleClick" />
            <div v-for="(point, index) in points" :key="index" class="marker"
                :style="{ left: point.x + 'px', top: point.y + 'px' }"></div>
            <div v-for="facility in facilities" :key="facility.id" class="facility" :style="getFacilityStyle(facility)">
                <div class="facility-name">{{ facility.name }}</div>
            </div>
            <div class="card-container">
                <h1>当前任务</h1>
                <div class="cards">
                    <div v-if="todoList.length !== 0" v-for="todo in todoList" :key="todo.id" class="card">
                        <div class="card-header">
                            <h4>{{ todo.title }}</h4>
                            <span :class="['status-text', getStatusClass(todo.status)]">
                                {{ getStatusText(todo.status) }}
                            </span>
                        </div>
                        <p>{{ todo.task }}</p>
                        <el-progress :percentage="todo.isCompleted" />
                        <p>奖惩: {{ todo.item }}</p>
                        <!-- <p>优先级: {{ todo.priority }}</p> -->
                        <p>截止时间: {{ formatDate(todo.dueDate) }}</p>
                    </div>
                    <div v-else class="no-data">
                        <p>暂时没有任务哦</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>
<script setup>
import { ref, onMounted, reactive } from 'vue';
import mapImage from '@/assets/images/cduNew.png'; // 使用 import 引入图片
import { listFacilities, addFacility, updateFacility, deleteFacility } from "@/api/facility";
//根据商店id获取当前商店的服务和商品
import { getGoodsListByStoreId } from "@/api/product";
//根据设施id获取当前设施的事件
import { getEventByFacilityId } from "@/api/event";
//根据设施id获取当前设施的活动
import { getActivitiesByFacilityId } from "@/api/activity";
//根据设施id获取当前设施的商店
import { getStoresByFacilityId } from "@/api/virtualStore";

//根据用户id获取用户的奖惩表
import { getRewardPunishmentByUserId } from "@/api/rewardPunishment"
import eventApi from '@/api/todoEvent'

const todoList = ref([]);

const fetchTodoList = async () => {
    try {
        const response = await eventApi.getEventListByUserId(); // 假设你的 API 路径是这个
        todoList.value = response.data; // 将获取的数据赋值给 todoList
    } catch (error) {
        console.error('获取待办事项失败:', error);
    }
};

// 格式化日期
const formatDate = (date) => {
    return new Date(date).toLocaleString();
};



// const calculateProgress = (isCompleted) => {
//     return isCompleted ? 100 : 0; // 根据 isCompleted 返回进度
// };
function statusClass(startDate, dueDate) {
    const now = new Date();
    const start = new Date(startDate);
    const due = new Date(dueDate);
    return now >= start && now <= due ? 'status-green' : 'status-red';
}

function timeUntilStart(startDate) {
    const now = new Date();
    const start = new Date(startDate);
    const diff = start - now;

    if (diff <= 0) {
        return '已开始';
    }

    const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));

    return `${hours} 小时 ${minutes} 分钟`;
}

const getStatusText = (status) => {
    switch (status) {
        case 0: return '未开始';
        case 1: return '正在进行';
        case 2: return '未完成';
        case 3: return '失败';
        default: return '未知状态';
    }
};

const getStatusClass = (status) => {
    return `status-${status}`;
};


onMounted(() => {
    fetchTodoList(); // 组件挂载后获取待办事项
});


// 使用 ref 定义响应式数据
const mapSrc = mapImage;
const points = ref([]); // 存储点击的相对坐标
const imageWidth = ref(0);
const imageHeight = ref(0);
const loading = ref(false);
const facilities = ref([]); // 设施列表
const facilityTitle = ref(""); // 设施名称
const goodsList = ref([]); // Store goods and services
const eventsList = ref([]); // Store events
const activitiesList = ref([]); // Store activities
const rewardPunishmentList = ref([]); // Store reward and punishment
const storesList = ref([]); // Store stores
const facility = ref({}); // 当前点击的设施
const queryParams = reactive({
    name: "",
    type: undefined,
});


// 查询设施列表
const getList = () => {
    loading.value = true;
    listFacilities(queryParams).then(response => {
        facilities.value = response.data;
        console.log("设施列表:", response.data);
        loading.value = false;
    });
};

//查询当前用户的奖惩表
const getRewardPunishment = () => {
    getRewardPunishmentByUserId().then(response => {
        console.log("当前用户的奖惩表:", response.data);
        rewardPunishmentList.value = response.data;
    });
};


// 设施数据

const clickPoints = ref([]); // 存储所有点击的坐标
const groupedPoints = ref([]); // 存储每四个点击的坐标组

const handleClick = (event) => {
    //打印照片宽高
    console.log(`Image width: ${imageWidth.value}, height: ${imageHeight.value}`);
    // const x = (event.offsetX / imageWidth.value) * 800; // 计算相对位置
    // const y = (event.offsetY / imageHeight.value) * 600; // 计算相对位置
    const x = event.offsetX
    const y = event.offsetY
    console.log(`x,y: (${x}, ${y})`);
    console.log(`event.offsetX: ,event.offsetY: (${event.offsetX}, ${event.offsetY})`);

    // 存储点击的点
    points.value.push({ x: event.offsetX, y: event.offsetY });

    // 检查点击位置是否在某个设施内部
    const clickedFacility = facilities.value.find(facility => isInsideFacility(x, y, facility));
    if (clickedFacility) {
        alert(`你点击了: ${clickedFacility.name}`);
        //打印facility
        console.log("当前设施信息:", clickedFacility);
        //检查是否存在关联的商店id并获取当前商店的服务和商品以及事件
        // if(clickedFacility.storeId!==0){
        //   //TODO: 获取当前商店的服务和商品以及事件
        //   console.log("当前商店的id:",clickedFacility.storeId);
        //   facilityTitle.value = clickedFacility.name;
        //   facility.value = clickedFacility;
        //   getGoodsListByStoreId(clickedFacility.storeId).then(response => {
        //     console.log("当前商店的服务和商品以及事件:",response.data);
        //     goodsList.value = response.data;
        //   }); 
        //打印商品列表
        // console.log("当前商店的商品列表:",response.data);

        //}
        //检查当前位置是否存在事件
        //TODO: 获取当前位置的事件
        getEventByFacilityId(clickedFacility.id).then(response => {
            console.log("当前设施的事件:", response.data);
            eventsList.value = response.data;
        });
        //检查当前位置是否存在活动
        //TODO: 获取当前位置的活动
        getActivitiesByFacilityId(clickedFacility.id).then(response => {
            console.log("当前设施的活动:", response.data);
            activitiesList.value = response.data;
        });
        //检查当前位置是否存在商店
        //TODO: 获取当前位置的商店
        getStoresByFacilityId(clickedFacility.id).then(response => {
            console.log("当前设施的商店:", response.data);
            storesList.value = response.data;
        });





    } else {
        console.log(`Clicked at coordinates: (${x}, ${y})`);
    }
    // 存储每次点击的坐标
    clickPoints.value.push({ x, y });

    // 每四次点击组合一个坐标组
    if (clickPoints.value.length % 4 === 0) {
        const points = clickPoints.value.slice(-4); // 获取最近的四个点
        const formattedPoints = formatPoints(points);
        groupedPoints.value.push(formattedPoints); // 存储格式化的坐标组
        console.log(`Stored points group:`, formattedPoints);
    }


};



const formatPoints = (points) => {
    return points.map(point => `(${point.x}, ${point.y})`);
};

// 检查点击位置是否在设施的矩形区域内
const isInsideFacility = (x, y, facility) => {
    const coordinates = parseLocation(facility.location);
    const [topLeft, topRight, bottomRight, bottomLeft] = coordinates;

    // 确定矩形的边界
    const minX = Math.min(topLeft[0], bottomLeft[0]);
    const maxX = Math.max(topRight[0], bottomRight[0]);
    const minY = Math.min(topLeft[1], topRight[1]);
    const maxY = Math.max(bottomLeft[1], bottomRight[1]);

    return x >= minX && x <= maxX && y >= minY && y <= maxY;
};

//解析位置字符串为坐标数组
const parseLocation = (location) => {
    // 去掉字符串中的空格、单引号和双引号
    console.log("原始坐标字符串:", location);
    location = location.replace(/['"\s]+/g, '');

    // 将方括号转换为圆括号
    location = location.replace(/\[/g, '(').replace(/\]/g, ')');

    const matches = location.match(/\((\d+),(\d+)\)/g);
    return matches.map(match => match.replace(/[()]/g, '').split(',').map(Number));
};

// 根据设施的坐标计算样式
// const getFacilityStyle = (facility) => {
//   const coordinates = parseLocation(facility.location);
//   const [topLeft, topRight, bottomRight, bottomLeft] = coordinates;

//   const width = topRight[0] - topLeft[0]; // 宽度
//   const height = bottomLeft[1] - topLeft[1]; // 高度

//   return {
//     position: 'absolute',
//     left: topLeft[0] + 'px',
//     top: topLeft[1] + 'px',
//     width: width + 'px',
//     height: height + 'px',
//     backgroundColor: 'rgba(255, 0, 0, 0.3)', // 半透明背景
//     border: '1px solid red', // 红色边框
//     borderRadius: '4px'
//   };
// };
const getFacilityStyle = (facility) => {
    const coordinates = parseLocation(facility.location);
    if (!coordinates) {
        console.warn(`Invalid location for facility: ${facility.name}`);
        return {}; // 返回空样式以避免错误
    }

    // 获取多边形的边界
    const left = Math.min(...coordinates.map(coord => coord[0]));
    const top = Math.min(...coordinates.map(coord => coord[1]));
    const right = Math.max(...coordinates.map(coord => coord[0]));
    const bottom = Math.max(...coordinates.map(coord => coord[1]));

    // 计算多边形的宽度和高度
    const width = right - left;
    const height = bottom - top;

    // 使用 clipPath 定义多边形
    const polygonPoints = coordinates.map(coord => {
        return `${(coord[0] - left) / width * 100}% ${(coord[1] - top) / height * 100}%`;
    }).join(', ');

    return {
        position: 'absolute',
        left: left + 'px',
        top: top + 'px',
        width: width + 'px',
        height: height + 'px',
        backgroundColor: 'rgba(255, 0, 0, 0.3)', // 半透明背景
        border: '1px solid red', // 红色边框
        borderRadius: '1px',
        clipPath: `polygon(${polygonPoints})` // 使用 clipPath 定义多边形
    };
};


// 获取图片尺寸
const setImageDimensions = () => {
    const img = new Image();
    img.src = mapSrc;
    img.onload = () => {
        imageWidth.value = img.width;
        imageHeight.value = img.height;
    };
};

// 在组件挂载时获取图片尺寸
onMounted(() => {
    setImageDimensions();
    getRewardPunishment();
});

// 初始化设施列表
getList();
</script>
<style>
.flex-container {
    display: flex;
    /* Use flexbox for layout */
    min-width: 1420px;
    /* Set minimum width */
    max-width: 1500px;
    /* align-items: flex-start; */
    /* Align items at the start */
    /* flex-direction: column; */
    /* Stack items vertically */
}

.map-container {
    display: flex;
    position: relative;
    width: 100%;
    /* flex-direction: row; */
    /* 从左向右排列 */

    /* 根据图片宽度自适应 */
    height: auto;
    /* 根据图片高度自适应 */
}



.map-image {
    display: block;
    /* 确保图片是块级元素 */
    width: 1077px;
    /* 适应容器宽度 */
    max-height: 100%;
    /* 适应容器 */
    border-radius: 10px 10px;
}

.marker {
    position: absolute;
    width: 20px;
    height: 20px;
    background-color: red;
    border-radius: 50%;
    transform: translate(-50%, -50%);
}

.facility {
    position: absolute;
    pointer-events: none;
    /* Disable pointer events for facilities */
}

.facility-name {
    color: white;
    font-weight: bold;
    font-size: 15px;
    text-align: center;
    margin-top: 5px;
}


.status-green {
    display: inline-block;
    width: 10px;
    height: 10px;
    background-color: green;
    border-radius: 50%;
    margin-right: 5px;
}

.status-red {
    display: inline-block;
    width: 10px;
    height: 10px;
    background-color: red;
    border-radius: 50%;
    margin-right: 5px;
}


.info-columns {
    display: flex;
    /* 使用 flexbox 布局 */
    /* justify-content: space-between; */
    /* 分散排列 */
}

.info-column {
    flex: 1;
    /* 每列占相等宽度 */
    margin: 0 10px;
    /* 列间距 */
}

.stores-list,
.events-list,
.activities-list {
    max-height: 800px;
    /* 设置最大高度 */
    overflow-y: auto;
    /* 纵向滚动条 */
    margin-bottom: 15px;
    /* 每个部分之间的间距 */
}



.el-form-item {
    margin-bottom: 20px;
}

.el-input,
.el-select,
.el-date-picker {
    border-radius: 4px;
    box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1);
}

.card-container {
    margin-top: 10px;
    background: #f5f5f5;
    border: 1px solid #ccc;
    min-width: 300px;
    max-width: 400px;
    border-radius: 8px;
    padding: 10px;
    flex-grow: 1;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.cards {
    display: flex;
    flex-direction: column;
}

.card {
    margin-bottom: 10px;
    padding: 15px;
    border: 1px solid #eee;
    border-radius: 4px;
    background-color: #fff;
    transition: box-shadow 0.3s, transform 0.3s;
}

.card:hover {
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
    transform: translateY(-2px);
}

.card h4 {
    margin: 0 0 5px;
    font-size: 1.2rem;
    color: #333;
}

.card p {
    margin: 5px 0;
    font-size: 0.9rem;
    color: #666;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.status-text {
  margin-right: 10px; /* Space between text and dot */
  font-size: 0.9rem;
}

.status-dot {
  width: 10px;
  height: 10px;
  border-radius: 50%;
}

.status-0 {
  /* background-color: #f39c12; 未开始 */
  color: #f39c12; /* Adjust text color */
}

.status-1 {
  /* background-color: #3498db; 正在进行 */
  color: #3498db; /* Adjust text color */
}

.status-2 {
  /* background-color: #e67e22; 未完成 */
  color: #e67e22; /* Adjust text color */
}

.status-3 {
  /* background-color: #e74c3c; 失败 */
  color: #e74c3c; /* Adjust text color */
}



.no-data {
    text-align: center;
    color: #999;
    font-size: 1rem;
}
</style>